import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:juju/conf/IMConf.dart';
import 'package:juju/default/Kits.dart';
import 'package:juju/fake/fake_message_tool.dart';
import 'package:juju/model/ChatDataModel.dart';

class ContactsPage extends StatefulWidget {
  const ContactsPage({Key? key}) : super(key: key);

  @override
  State<ContactsPage> createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  List<UserInfo> _friends = [];
  ChatDataModel dataModel = ChatDataModel();

  @override
  void initState() {
    print(
        "========================== ContactsPage : init ======================");
    super.initState();
    _getFriendList();
  }

  @override
  Widget build(BuildContext context) {
    print(
        "========================== ContactsPage : build ======================");
    return Scaffold(
      appBar: AppBar(
        title: const Text("通讯录"),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.add_circle_outline),
            onPressed: _gotoAddFriendPage,
          )
        ],
      ),
      body: Container(
        color: Colors.grey[50],
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: _friends.length,
        ),
      ),
    );
  }

  ///========================================
  /// 会话列表构建器
  ///========================================
  Widget _itemBuilder(BuildContext buildContext, int position) {
    print(
        "========================== item contact : build ======================");
    return Container(
      padding: const EdgeInsets.only(
        top: 5.0,
        bottom: 5.0,
      ),
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: ListTile(
        leading: Container(
          clipBehavior: Clip.hardEdge,
          // padding: EdgeInsets.all(5.0),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15.0),
          ),
          child: avatar(_friends.elementAt(position).avatarThumbPath),
        ),
        // leading: dataList.elementAt(position),
        // leading: Icon(Icons.account_circle),
        title: Text(_friends.elementAt(position).username),
        onTap: () => _startChat(friendIndex: position),
      ),
    );
  }

  void _gotoAddFriendPage() {
    Navigator.of(context).pushNamed("AddFriend");
  }

  void _getFriendList() async {
    await IMConf.getInstance().getJmessage().getFriends().then(
      (value) {
        setState(() {
          _friends = value;
        });
        print("=================== 获取好友列表 =====================");
        int i = 0;
        for (UserInfo u in value) {
          i++;
          print("|\n|\n----- 好友$i : ${u.toJson()}\n");
        }
      },
      onError: (e) {
        if (e is PlatformException) {
          print("=================== 获取好友列表失败 =====================");
          print("|\n|\n----- ${e.code}");
          print("|\n|\n----- ${e.details}");
          print("|\n|\n----- ${e.message}");
        }
      },
    );
  }

  void _startChat({required int friendIndex}) async {
    Single target = Single.fromJson({
      'username': _friends[friendIndex].username,
    });
    dataModel.target = target;
    IMConf.getInstance().getJmessage().getConversation(target: target).then(
      (conversation) {
        print(
            "====================== 成功获取会话 ====================|\n|\n----- 跳转中。。。");
        dataModel.conversationInfo = conversation;
        _getHistorMessage(selectConversationInfo: conversation);
        Navigator.of(context).pushNamed("ChatPage", arguments: dataModel);
      },
      onError: (e) {
        IMConf.getInstance()
            .getJmessage()
            .createConversation(target: target)
            .then(
          (conversation) {
            print(
                "====================== 成功创建会话 ====================|\n|\n----- 跳转中。。。");
            ChatDataModel dataModel = ChatDataModel();
            dataModel.conversationInfo = conversation;
            Navigator.of(context).pushNamed("ChatPage", arguments: dataModel);
          },
          onError: (e) {
            if (e is PlatformException) {
              PlatformException ex = e;
              print(ex.code);
              print(ex.details);
              print(ex.message);
            } else {
              print(e.toString());
            }
          },
        );
      },
    );
  }

  ///========================================
  /// 历史消息
  ///========================================
  void _getHistorMessage(
      {required ConversationInfo selectConversationInfo}) async {
    print("getHistorMessage");

    await selectConversationInfo
        .getHistoryMessages(from: 0, limit: 20)
        .then((msgList) {
      setState(() {
        dataModel.msgList = msgList;
      });
      // chatDataModel.msgListSet(msgList);
    });
  }
}
